//
//  SearchController.m
//  dierzu_10_30
//
//  Created by lanou3g on 15/10/30.
//  Copyright © 2015年 仝肖月. All rights reserved.
//搜索记录
//        [self.rootView.searchTableView reloadData];
//        NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)firstObject];
//        path = [path stringByAppendingString:@"/title_message.txt"];
//        NSData *data = [NSData dataWithContentsOfFile:path];
//        NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
//        NSMutableArray *array = [unarchiver decodeObjectForKey:@"title"];
//        [unarchiver finishDecoding];
//        cell.textLabel.text = [array objectAtIndex:indexPath.row];


//存在问题:当输入的内容搜不到时会崩溃




#import "SearchController.h"
#import "RootView.h"
#import "UIImage+Extension.h"

@interface SearchController()<UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate>
@property(nonatomic,strong)RootView *rootView;
@property(nonatomic,strong)UITextField *searchBar;
//用来保存所有的电影名字
@property(nonatomic,strong)NSMutableArray *dataArray;
//用来保存搜索记录
@property(nonatomic,strong)NSMutableArray *searchedArray;
@end

@implementation SearchController

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.searchBar = [[UITextField alloc] init];
        self.dataArray = [NSMutableArray array];
        self.searchedArray = [NSMutableArray array];
    }
    return self;
}

-(void)loadView
{
    self.rootView = [[RootView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.view = self.rootView;
}
-(void)viewDidLoad
{
    [super viewDidLoad];
    
    //设置代理
    self.rootView.searchTableView.delegate = self;
    self.rootView.searchTableView.dataSource = self;
    self.searchBar.delegate = self;
    
    [self createSearchBar];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [self.dataArray removeAllObjects];
        [self.rootView.searchTableView reloadData];
        //解析数据
        NSString *urlString = @"https://openapi.youku.com/v2/searches/keyword/top.json?client_id=51efa7f614d5a3ca";
        NSURLSession *session = [NSURLSession sharedSession];
        NSURLSessionTask *task = [session dataTaskWithURL:[NSURL URLWithString:urlString] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            NSDictionary *rootDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSArray *keywordsArray = rootDict[@"keywords"];
            for (NSDictionary *dict in keywordsArray) {
                [self.dataArray addObject:dict[@"keyword"]];
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.rootView.searchTableView reloadData];
            });
        }];
        [task resume];
        NSLog(@"%@",self.dataArray);
    });
    if (self.searchBar.text != nil) {
        [self.rootView.searchTableView reloadData];
    }
    
}
-(void)createSearchBar
{
    
    //---------------布局searchBar---------------------
    UIView *searchbarAndButtonView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 44)];
    self.navigationItem.titleView = searchbarAndButtonView;
    self.navigationController.navigationBar.translucent = YES;
    self.searchBar.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width-120, 35);
    //设置背景
    self.searchBar.background = [UIImage resizedImage:@"searchbar_textfield_background@2x"];
    //设置内容--垂直居中
    self.searchBar.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    self.searchBar.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    //设置左边显示一个放大镜
    UIImageView *leftView = [[UIImageView alloc] init];
    leftView.image = [UIImage imageNamed:@"searchbar_textfield_search_icon@2x"];
    leftView.frame = CGRectMake(0, 0, self.searchBar.frame.size.height, self.searchBar.frame.size.height);
    //设置leftView的内容居中
    leftView.contentMode = UIViewContentModeCenter;
    self.searchBar.leftView = leftView;
    //设置左边的View永远显示
    self.searchBar.leftViewMode = UITextFieldViewModeAlways;
    //设置右边永远显示清除按钮
    self.searchBar.clearButtonMode = UITextFieldViewModeAlways;
    [searchbarAndButtonView addSubview:self.searchBar];
    
    //搜索按钮
    UIButton *searchButton = [UIButton buttonWithType:UIButtonTypeCustom];
    searchButton.frame = CGRectMake(CGRectGetMaxX(self.searchBar.frame) , CGRectGetMinY(self.searchBar.frame), 50, 35);
    [searchButton setTitle:@"搜索" forState:UIControlStateNormal];
    [searchButton addTarget:self action:@selector(searchButtonDidClicked:) forControlEvents:UIControlEventTouchUpInside];
    [searchButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [searchbarAndButtonView addSubview:searchButton];
    //取消按钮
    UIButton *cancelButton = [UIButton buttonWithType:UIButtonTypeCustom];
    cancelButton.frame = CGRectMake(CGRectGetMaxX(searchButton.frame) , CGRectGetMinY(searchButton.frame), CGRectGetWidth(searchButton.frame), CGRectGetHeight(searchButton.frame));
    [cancelButton setTitle:@"取消" forState:UIControlStateNormal];
    [cancelButton addTarget:self action:@selector(cancelButtonDidClicked:) forControlEvents:UIControlEventTouchUpInside];
    [cancelButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [searchbarAndButtonView addSubview:cancelButton];
    
    //----------------------------------------------------
}

-(void)searchButtonDidClicked:(UIButton *)sender
{
    //回收键盘
    [self.searchBar resignFirstResponder];
    [self.dataArray removeAllObjects];
    [self.rootView.searchTableView reloadData];
    [self.searchedArray addObject:self.searchBar.text];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        //解析数据
        //去掉输入字符串前后空格
#warning 这里没有去掉输入框前后空格
        NSCharacterSet *whitespace = [NSCharacterSet whitespaceAndNewlineCharacterSet];
        [self.searchBar.text stringByTrimmingCharactersInSet:whitespace];
        
        NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:self.searchBar.text];
        NSString *titleString = [self.searchBar.text stringByAddingPercentEncodingWithAllowedCharacters:set];
        NSString *urlString = [NSString stringWithFormat:@"https://openapi.youku.com/v2/searches/video/by_keyword.json?client_id=51efa7f614d5a3ca&keyword=%@",titleString];
        NSURLSession *session = [NSURLSession sharedSession];
        NSURLSessionTask *task = [session dataTaskWithURL:[NSURL URLWithString:urlString] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            if (data == nil) {
#warning 这里没有弹窗
                UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"温馨提示!" message:@"你寻找的资源不存在" preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *alertAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
                [alertController addAction:alertAction];
            }else{
                NSError *erro = nil;
                NSDictionary *rootDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&erro];
                
                NSArray *videosArray = rootDict[@"videos"];
                for (NSDictionary *dict in videosArray) {
                    [self.dataArray addObject:dict[@"title"]];
                }
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self.rootView.searchTableView reloadData];
                });
            }
        }];
        [task resume];
        
    });
    NSLog(@"%@",self.dataArray);
}
-(void)cancelButtonDidClicked:(UIButton *)sender
{
    [self.searchBar resignFirstResponder];
    [self.navigationController popToRootViewControllerAnimated:YES];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cell_id = @"flag";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cell_id];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cell_id];
    }
    cell.textLabel.text = [self.dataArray objectAtIndex:indexPath.row];
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //让tableView取消选中状态
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    //取出选中行的内容
    NSString *string = self.dataArray[indexPath.row];
    //把选中的内容显示到输入框
    self.searchBar.text = string;
}




@end
